package com.santiao.youxiang.ui.fragment

import android.annotation.SuppressLint
import android.app.Dialog
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.fragment.app.Fragment
import com.santiao.youxiang.bean.YibaoBean

//import com.santiao.youxiang.databinding.FragmentMainBinding
import com.santiao.youxiang.event.XXLEvent
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import androidx.recyclerview.widget.LinearLayoutManager
import com.allen.library.shape.ShapeTextView
import com.santiao.youxiang.MainActivity
import com.santiao.youxiang.bean.PostBean
import com.santiao.youxiang.ext.thrillClickListener

import com.santiao.youxiang.R
import com.santiao.youxiang.database.hleper.PostDatabaseHelper
import com.santiao.youxiang.databinding.FragmentAddEmailBinding
//import com.santiao.youxiang.database.Bill

import com.santiao.youxiang.ui.activity.SelectAccountActivity
import com.santiao.youxiang.ui.adapter.AccountItemAdapter
import com.santiao.youxiang.ui.widget.LoadingDiaLog
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.Properties
import javax.mail.Folder
import javax.mail.Session

//import com.santiao.youxiang.databinding.FramentShebaoBillBinding


class emailAcountFragment : Fragment(){

    var binding : FragmentAddEmailBinding?=null

    var groupedByMonth: Map<String, List<YibaoBean>>?=null

    private lateinit var HviewModel: HomeViewModel

//    private val HviewModel: HomeViewModel by viewModels()
//    val HviewModel = ViewModelProvider(requireActivity()).get(HomeViewModel::class.java)
    private lateinit var Aadapter: AccountItemAdapter

    private lateinit var water_container: FrameLayout
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentAddEmailBinding.inflate(inflater, container, false)
        return binding!!.root
    }

    @SuppressLint("NewApi")
    @RequiresApi(Build.VERSION_CODES.M)
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)


        if(!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        initView(view)

        initdata()
        initClick()
        initRv()

    }
    private fun initView(view: View){
        HviewModel= MainActivity.HviewModel

    }

    fun initRv(){


        Aadapter=AccountItemAdapter()


        val layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
        Log.e("initrv: ", "2")
//        Camadapter

        binding!!.rvAccount?.layoutManager = layoutManager
        binding!!.rvAccount?.adapter = Aadapter

        Aadapter!!.setOnItemClickListener { adapter, view, position ->



            if (HviewModel.currentPost.value!=Aadapter.data[position].pid){
                val databaseHelper=PostDatabaseHelper(requireContext(),HviewModel)
                val oldCurrent=databaseHelper.getCurrentPost()
                if (oldCurrent!=null){
                    databaseHelper.updatePost(PostBean(oldCurrent.pid,oldCurrent.pAddress,oldCurrent.pCode,false))
                    databaseHelper.updatePost(PostBean(Aadapter.data[position].pid,Aadapter.data[position].pAddress,Aadapter.data[position].pCode,true))
                    HviewModel.currentPost.value=Aadapter.data[position].pid
                }
            }

                    var mainActivity = requireActivity() as MainActivity
                    mainActivity.smoothToHome();

//            Log.e("initRv: ","1" )
//
//            var hab = LitePal.where("id = ?", Aadapter.data[position].id.toString()).findFirst(habitBill::class.java)
//
//            checkInDialog(hab)
//
//            Log.e("initRv: ",hab.toString() )


        }

        Aadapter!!.setOnItemChildClickListener { _, view, position ->



            if (view.id == R.id.iv_del) {
                // 删除逻辑
//                delFromdb(Aadapter!!.data.get(position).id.toString())
//                Aadapter!!.removeAt(position)
//                Aadapter!!.notifyItemRemoved(position)


                deldialog(Aadapter.data.get(position).pid!!.toLong())



            }

//            if (view.id == R.id.ll_edit) {
//                // 编辑逻辑
////                delFromdb(billadapter!!.data.get(position).id.toString())
////                billadapter!!.removeAt(position)
////                billadapter!!.notifyItemRemoved(position)
//                HabitEditActivity.startActivity(requireContext(),"2",Aadapter!!.data.get(position).id.toString())
//
//            }

//            val bundle=Bundle()
//            bundle.putInt("type", type)
//            bundle.putSerializable("email", itemData)
//            LZYBaseActivity.forward<EmailDetailActivity>(mContext,bundle)

        }


    }


    private fun deldialog(pid:Long) {
        val dialog = Dialog(requireContext(), R.style.MyDialog)
//        dialog.setCancelable(false)
//        dialog.setCanceledOnTouchOutside(false)
        dialog.setContentView(R.layout.dialog_del);
//        updateTextColor(dialog)
        dialog.window?.setLayout(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        //底部弹出的Dialog
        dialog.window?.setGravity(Gravity.CENTER);
        var tvtitle=dialog.findViewById<TextView>(R.id.tv_title)
        var tvdes=dialog.findViewById<TextView>(R.id.tv_des)
//        var etdes=dialog.findViewById<EditText>(R.id.et_des)
        var close=dialog.findViewById<ShapeTextView>(R.id.tv_cancel)
//        var checkin=dialog.findViewById<ShapeTextView>(R.id.tv_check)
        var confrim=dialog.findViewById<ShapeTextView>(R.id.tv_confrim)

        dialog.show()

        close.thrillClickListener {
            dialog.cancel()
        }

        confrim.thrillClickListener {
            val databaseHelper=PostDatabaseHelper(requireContext(),HviewModel)
            databaseHelper.deletePost(pid)
            if (HviewModel.postList.value?.size==1){
                val data=databaseHelper.getAllPosts()
                HviewModel.postList.value=data
                HviewModel.currentPost.value=-1
                HviewModel.currentPostType.value="none"
                HviewModel.cleanHome.value=true
                HviewModel.emailList.value= mutableListOf()
            }else{
                val pid=databaseHelper.setFirstPostAsCurrent()
                HviewModel.currentPost.value=pid
            }
            dialog.dismiss()
//            dialog.cancel()
        }


    }




    @RequiresApi(Build.VERSION_CODES.O)
    override fun onResume() {
        super.onResume()
        initdata()
    }


    fun initClick(){

        binding!!.postAdd.thrillClickListener {
            SelectAccountActivity.startActivity(requireContext())

        }

//        binding!!.ivCompute.thrillClickListener {
//            binding!!.ivBill.setImageResource(R.drawable.ic_shebao_bg9)
//            binding!!.ivCompute.setImageResource(R.drawable.ic_shebao_bg12)
//            binding!!.llBill.visibility= View.GONE
//            binding!!.llShebao.visibility= View.VISIBLE
//
//        }



    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageSimple(t: XXLEvent) {

    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }


    fun initdata(){

        HviewModel.postList.observe(viewLifecycleOwner){list->
            Log.e("initdata: ",list.toString() )


            Aadapter.data.clear()
            Aadapter.setList(list)
            if (Aadapter.data.isNullOrEmpty()){

            }else binding!!.llAccount.visibility= View.VISIBLE

            Aadapter.notifyDataSetChanged()

        }
        HviewModel.currentPost.observe(viewLifecycleOwner){

            Log.e( "initdata: ", it.toString())

            if (it!=-1L){
                val current=HviewModel.postList.value?.first { its-> its.pid==it }
                if (current!=null){
//                    LZYLog.i("lzyemail","当前邮箱:${current.pAddress}")
                    tryToLoginEmail0(current.pAddress,current.pCode)
                }
            }
        }
//        HviewModel.currentPostType.observe(viewLifecycleOwner){
////            when(it){
////                "none" ->{
////                    binding.postFun.visibility=View.GONE
////                    binding.postDel.visibility=View.GONE
////                }
////                "126","163" ->{
////                    binding.postFun.visibility=View.VISIBLE
////                    binding.postFunBad.visibility=View.VISIBLE
////                    binding.postDel.visibility=View.VISIBLE
////                }
////                "qq" , "aliyun" ->{
////                    binding.postFun.visibility=View.VISIBLE
////                    binding.postFunBad.visibility=View.GONE
////                    binding.postDel.visibility=View.VISIBLE
////                }
////                else ->{
////                    binding.postFun.visibility=View.GONE
////                    binding.postFunBad.visibility=View.GONE
////                    binding.postDel.visibility=View.GONE
////                }
////            }
//        }
    }


    @OptIn(DelicateCoroutinesApi::class)
    fun tryToLoginEmail0( email: String, authCode: String) {
        val loadingDiaLog= LoadingDiaLog(requireContext(),"连接中...")
        loadingDiaLog.show()
        // 在后台线程执行 IMAP 请求
        GlobalScope.launch(Dispatchers.IO) {
            var imapHost: String? =null
            val domain = email.substringAfter("@")
            when (domain) {
                "126.com" -> {
                    imapHost = "imap.126.com"
                }

                "163.com" -> {
                    // 对136.com进行处理
                    imapHost = "imap.163.com"
                }

                "qq.com" -> {
                    // 对qq.com进行处理
                    imapHost = "imap.qq.com"
                }

                else -> {
                    imapHost = "imap.aliyun.com"
                }
            }
            val imapPort = "993"
            val properties = Properties()
            properties["mail.store.protocol"] = "imaps"
            properties["mail.imaps.host"] = imapHost
            properties["mail.imaps.port"] = imapPort

            // 获取Session
            val session = Session.getInstance(properties)
            try {
                // 创建 IMAP 存储连接
                val store = session.getStore("imaps")
                store.connect(imapHost, email, authCode)  // 使用授权码登录

                // 获取所有文件夹
                val folder = store.defaultFolder
                val folders = folder.list("*")  // 获取所有文件夹，包括子文件夹
                for (f in folders) {
//                    LZYLog.i("lzyemailtest","${f.name}")
//                    store as IMAPStore
//                    val idMap: MutableMap<String, String> = HashMap()
//                    idMap["name"] = "mail poster" // 这里是一个姓名，可以随便写
//                    idMap["version"] = "7.26"
//                    idMap["os"] = "android"
//                    idMap["os-version"] = "1.0.0"
//                    idMap["vendor"] = "hello" // 随便写
//                    idMap["contact"] = "${email}" // 是一个邮箱
//                    store.id(idMap)
                    if (imapHost == "imap.aliyun.com")
                        f.open(Folder.READ_ONLY)  // 打开文件夹（只读模式）
//                    when (f.name) {
//                        "INBOX" -> {
//                            if (imapHost == "imap.aliyun.com")
//                                binding.postFunGetNum.text = "${f.messages.size}"
//                            else
//                                binding.postFunGetNum.text = "${f.messageCount}"
//                        }
//
//                        "草稿箱", "Drafts" , "草稿" -> {
//                            if (imapHost == "imap.aliyun.com")
//                                binding.postFunKeepNum.text = "${f.messages.size}"
//                            else
//                                binding.postFunKeepNum.text = "${f.messageCount}"
//                        }
//
//                        "已发送", "Sent Messages" -> {
//                            if (imapHost == "imap.aliyun.com")
//                                binding.postFunSendNum.text = "${f.messages.size}"
//                            else
//                                binding.postFunSendNum.text = "${f.messageCount}"
//                        }
//
//                        "已删除", "Deleted Messages" , "已删除邮件"-> {
//                            if (imapHost == "imap.aliyun.com")
//                                binding.postFunDelNum.text = "${f.messages.size}"
//                            else
//                                binding.postFunDelNum.text = "${f.messageCount}"
//                        }
//
//                        "垃圾邮件", "Junk" -> {
//                            if (imapHost == "imap.aliyun.com")
//                                binding.postFunTrashNum.text = "${f.messages.size}"
//                            else
//                                binding.postFunTrashNum.text = "${f.messageCount}"
//                        }
//
//                        "病毒文件夹", "病毒邮件" -> {
//                            binding.postFunBadNum.text = "${f.messageCount}"
//                        }
//                    }
//                    f.close()
                }
                store.close()
                withContext(Dispatchers.Main) {
                    loadingDiaLog.dismiss()
//                    Toast.makeText(requireContext(),"连接成功~", Toast.LENGTH_SHORT).show()
                    if (HviewModel.currentEmailType.value==6&&imapHost == "imap.qq.com") {
                        HviewModel.currentEmailType.value=1
                    }
                    when (domain) {
                        "126.com" -> {
                            HviewModel.currentPostType.value="126"
                        }

                        "163.com" -> {
                            // 对136.com进行处理
                            HviewModel.currentPostType.value="163"
                        }

                        "qq.com" -> {
                            // 对qq.com进行处理
                            HviewModel.currentPostType.value="qq"
                        }

                        else -> {
                            HviewModel.currentPostType.value="aliyun"
                        }
                    }
//                    var mainActivity = requireActivity() as MainActivity
//                    mainActivity.smoothToHome();
//                    myActivity.smoothToHome()
                }
            } catch (e: Exception) {
                e.printStackTrace()
//                LZYLog.i("lzyemail", "邮件：登录连接失败")
                withContext(Dispatchers.Main) {
                    loadingDiaLog.dismiss()
                    Toast.makeText(requireContext(),"连接失败！", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

}
